package com.example.dessert.controller.fore;

import com.example.dessert.annotation.LoginCheck;
import com.example.dessert.controller.BaseController;
import com.example.dessert.entity.*;
import com.example.dessert.service.*;
import com.example.dessert.util.ResponsePojo;
import com.example.dessert.util.ResultCode;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: OrderController
 * @Description:
 * @Author li
 * @Date 2022/1/18
 * @Version 1.0
 */
@Controller
@RequestMapping("/fore/order")
public class OrderController extends BaseController {

    @Resource
    private OrderService orderService;
    @Resource
    private ProductService productService;
    @Resource
    private ProductSpecService productSpecService;
    @Resource
    private AddressService addressService;
    @Resource
    private RegionService regionService;
    @Resource
    private CartService cartService;



    /**
     * 单件商品结算页（商品详情-立即购买）
     */
    @GetMapping("/buyByNow")
    @LoginCheck
    public String buyByNow(HttpSession session, Model model, @RequestParam Map<String, Object> map){

        logger.info("Buy Now Request Parameters:{}", map);

        Object userId = session.getAttribute("userId");
        Long productId = Long.parseLong(map.get("productId").toString());
        Long specId = Long.parseLong(map.get("specId").toString());
        Integer number = Integer.parseInt(map.get("number").toString());

        Product product = productService.queryProductBuyId(productId);

        ProductSpec spec = productSpecService.queryProductSpecBuyId(specId);

        //用户地址
        List<Address> address = addressService.queryAddressList((Long) userId);

        if(address.isEmpty()){
            List<Region> provinces = regionService.queryChildrenById(0L);
            model.addAttribute("provinces", provinces);
        }

        model.addAttribute("product", product);
        model.addAttribute("spec", spec);
        model.addAttribute("number", number);
        model.addAttribute("address", address);


        return "fore/order/buyByNow";

    }

    /**
     * 立即购买商品
     */
    @PostMapping("/placeOrderByNow")
    @LoginCheck
    @ResponseBody
    public ResponsePojo placeOrderByNow(HttpSession session, @RequestParam Map<String, Object> map) {

        logger.info("Buy items now Request Parameters:{}", map);

        Object userId = session.getAttribute("userId");
        Long productId = Long.parseLong(map.get("productId").toString());
        Long specId = Long.parseLong(map.get("specId").toString());
        Integer number = Integer.parseInt(map.get("number").toString());

        // 验证商品是否存在
        Product product = productService.queryProductBuyId(productId);
        if(product == null){
            return ResponsePojo.error(ResultCode.EXP_INVALID_PRODUCT,"商品不存在，请重新选择");
        }

        // 验证商品规格是否存在
        ProductSpec productSpec = productSpecService.queryProductSpecBuyId(specId);
        if(productSpec == null){
            return ResponsePojo.error(ResultCode.EXP_INVALID_PRODUCT_SPEC,"商品规格不存在，请重新选择");
        }


        //收货地址
        Address addressInfo = new Address();
        if (map.get("addressId") != null) {
            Long addressId = Long.parseLong(map.get("addressId").toString());
            addressInfo = addressService.queryAddressById(addressId);
        }else {
            addressInfo.setUserId((Long) userId)
                       .setContact((String)map.get("contact"))
                       .setMobile((String)map.get("mobile"))
                       .setProvince((String)map.get("province"))
                       .setCity((String)map.get("city"))
                       .setCounty((String)map.get("county"))
                       .setAddress((String)map.get("address"));
            addressService.storeAddress(addressInfo);
        }

        Long orderId = orderService.buyByProduct((Long) userId,product.getName(),productSpec.getName(),productSpec.getPrice(),number,addressInfo.getContact(),addressInfo.getMobile(),addressInfo.getProvince(),addressInfo.getCity(),addressInfo.getCounty(),addressInfo.getAddress());
        logger.info("Create User Address Information Results:{}", orderId);

        Map<String, Object> o = new HashMap<>();
        o.put("orderId", orderId);

        return ResponsePojo.ok(o);

    }


    /**
     * 订单列表
     */
    @GetMapping("/list")
    @LoginCheck
    public String list(HttpSession session,Model model, @RequestParam Map<String, Object> map ) {
        logger.info("Query user order request parameters:{}", map);

        int currPage = 1;
        int pageSize = ResultCode.DEFAULT_PAGE_SIZE;

        Object userId = session.getAttribute("userId");

        if (map.get("page") != null) {
            currPage = Integer.parseInt(map.get("page").toString());
        }

        int status = 0;
        if (map.get("status") != null) {
            status = Integer.parseInt(map.get("status").toString());
        }

        int startPage = (currPage - 1) * pageSize;

        List<Orders> orders= orderService.queryOrderPageByUser(startPage, pageSize,(Long) userId, status - 1);

        logger.info("Query query order page by user results :{}", orders);

        Long totalCount = orderService.queryOrderCountByUser((Long) userId, status - 1);

        long totalPage = (int) Math.ceil((double) totalCount / pageSize);

        model.addAttribute("orders", orders);
        model.addAttribute("currPage", currPage);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("status", status);

        return "fore/order/list";

    }

    /**
     * 订单详细
     */
    @GetMapping("/detailed")
    @LoginCheck
    public String detailed(HttpSession session,Model model, @RequestParam Map<String, Object> map ) {

        Object userId = session.getAttribute("userId");
        Long orderId = Long.parseLong(map.get("orderId").toString());

        Orders order= orderService.queryOrderByIdAndUserId((Long) userId,orderId);
        model.addAttribute("order", order);

        return "fore/order/detailed";
    }

    /**
     * 购物车商品结算页
     */
    @GetMapping("/buyByCart")
    @LoginCheck
    public String buyByCart(HttpSession session, Model model, @RequestParam Map<String, Object> map){

        logger.info("Buy by cart request parameters:{}", map);

        Object userId = session.getAttribute("userId");
        String cartIds = map.get("cartIds").toString();

        List<Cart> carts= cartService.queryCartListByIds((Long)userId,cartIds);
        logger.info("Query user cart List results :{}", carts);

        //用户地址
        List<Address> address = addressService.queryAddressList((Long) userId);

        if(address.isEmpty()){
            List<Region> provinces = regionService.queryChildrenById(0L);
            model.addAttribute("provinces", provinces);
        }

        int total =0;
        for (Cart cart : carts) {
            int price = cart.getSpecPrice() * cart.getNumber();
            total = total + price;
        }


        model.addAttribute("carts", carts);
        model.addAttribute("address", address);
        model.addAttribute("cartIds", cartIds);
        model.addAttribute("total", total);


        return "fore/order/buyByCart";

    }


    /**
     * 立即购买商品
     */
    @PostMapping("/placeOrderByCart")
    @LoginCheck
    @ResponseBody
    public ResponsePojo placeOrderByCart(HttpSession session, @RequestParam Map<String, Object> map) {

        logger.info("Buy items now Request Parameters:{}", map);

        Object userId = session.getAttribute("userId");
        String cartIds = map.get("cartIds").toString();

        //收货地址
        Address addressInfo = new Address();
        if (map.get("addressId") != null) {
            Long addressId = Long.parseLong(map.get("addressId").toString());
            addressInfo = addressService.queryAddressById(addressId);
        }else {
            addressInfo.setUserId((Long) userId)
                    .setContact((String)map.get("contact"))
                    .setMobile((String)map.get("mobile"))
                    .setProvince((String)map.get("province"))
                    .setCity((String)map.get("city"))
                    .setCounty((String)map.get("county"))
                    .setAddress((String)map.get("address"));
            addressService.storeAddress(addressInfo);
        }

        Long orderId = orderService.batchBuyByProduct((Long) userId,cartIds,addressInfo.getContact(),addressInfo.getMobile(),addressInfo.getProvince(),addressInfo.getCity(),addressInfo.getCounty(),addressInfo.getAddress());
        logger.info("Create User Address Information Results:{}", orderId);

        Map<String, Object> o = new HashMap<>();
        o.put("orderId", orderId);

        return ResponsePojo.ok(o);

    }


}
